package org.softmed.rest.editor;

import java.util.List;

import org.softmed.filehandling.CodeUtil;
import org.softmed.rest.admin.file.FileManager;

import restlet.description.convert.RESTConfigurationDescription;
import restlet.description.convert.RESTConfigurationXMLConverter;
import restlet.description.convert.RESTModuleDescription;

public class RESTConfigurationManager {

	RESTConfigurationXMLConverter converter = new RESTConfigurationXMLConverter();
	FileManager fileManager;
	String configFilePath;
	RESTConfigurationDescription description;

	public RESTConfigurationDescription loadConfigurationFile(String path)
			throws Throwable {
		String xml = fileManager.readFile(path);
		description = (RESTConfigurationDescription) converter.fromXML(xml);
		return description;
	}

	public void loadModules(RESTConfigurationDescription description)
			throws Throwable {
		List<String> moduleSources = description.getModuleConfigurationFiles();
		for (String path : moduleSources) {
			description.addModule(loadModule(path));
		}
	}

	public RESTModuleDescription loadModule(String path) throws Throwable {
		String xml = fileManager.readFile(path);
		RESTModuleDescription module = (RESTModuleDescription) converter
				.fromXML(xml);
		module.setPath(path);
		return module;
	}

	public void saveConfigurationFile(RESTConfigurationDescription description, String path) throws Throwable {
		description.compile();
		String xml = converter.toXML(description);
		fileManager.saveToFile(path, xml);
		this.description = description;
	}

	public void saveModule(RESTModuleDescription description)
			throws Throwable {
		String xml = converter.toXML(description);
		fileManager.saveToFile(description.getPath(), xml);
	}

	public void removeModule(String path) {
		description.getModuleConfigurationFiles().remove(path);
		// description.get
	}

	public String loadHandler(String path) throws Throwable {
		return fileManager.readFile(path);
	}

	public void saveHandler(String path, String code) throws Throwable {
		fileManager.saveToFile(path, code);
	}

	public String getConfigFilePath() {
		return configFilePath;
	}

	public void setConfigFilePath(String configFilePath) {
		this.configFilePath = configFilePath;
	}

	public RESTConfigurationDescription getDescription() {
		return description;
	}

	public void setDescription(RESTConfigurationDescription description) {
		this.description = description;
	}

	public FileManager getFileManager() {
		return fileManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}

}
